//
//  HMHomeViewController.swift
//  iOSWeibo12
//
//  Created by Admin on 16/9/11.
//  Copyright © 2016年 itcast. All rights reserved.
//

import UIKit
import SVProgressHUD
import SVPullToRefresh

let OriginalCellIdentifier = "OriginalCell"
let RetweetCellIdentifier = "RetweetCell"

class HMHomeViewController: HMBaseViewController {
    
    // MARK: - 属性
    /// 微博模型数组
    var statusVMs: [HMStatusViewModel]? {
        didSet {
            tableView.reloadData()
        }
    }

    override func viewDidLoad() {
        super.viewDidLoad()

        if !userLogin {
            print("用户没有登录")
            return
        }
        
//        UIApplication.shared.keyWindow?.showInCenter()
        
        setupNavigation()
        setupTabelView()
    }
    
    /**
     加载新的微博数据
     */
    func loadNewData() {
        print("加载新的微博数据")
        // 获取id最大的微博, 如果没有数据,就默认加载最新20条微博数据
        let since_id = statusVMs?.first?.status.id ?? 0
        
        // 加载微博数据
        HMStatusListViewModel.shared.loadStatus(since_id: since_id, max_id: 0) { (statusVMs: [HMStatusViewModel]?, error: Error?) in
            
            // 关闭下拉刷新控件
            self.refreshView.endRefreshing()
            
            // 判断错误
            if error != nil {
                print("加载微博数据出错了: \(error)")
                SVProgressHUD.showError(withStatus: "加载微博数据失败,网络不给力")
                return
            }
            
            // 获取到多少条微博数据
            let count = statusVMs?.count ?? 0
            
            // 下拉刷新,显示加载了多少条微博
            if since_id > 0 {
                self.showTipView(count: count)
            }
            
            // 没有加载微博数据
            if count == 0 {
                print("没有新的微博数据")
                return
            }
            
            // 如果是下拉刷新,将获取到数据拼接在现有数据的前面
            if since_id > 0 {   // 下拉刷新
                // 最新数据 =  新获取到的数据 + 原有的数据
                print("下拉刷新,获取到: \(statusVMs?.count)");
                self.statusVMs = statusVMs! + self.statusVMs!
            } else {
                // 刚进入程序,加载最新的微博数据
                // 最新数据 = 新获取到的数据
                self.statusVMs = statusVMs
                print("获取最新20条数据.获取到 \(statusVMs?.count) 条微博")
                
                // 上拉加载更多
                self.tableView.addInfiniteScrolling {
                    self.loadMoreStatus()
                }
            }
        }
    }
    
    private func showTipView(count: Int) {
        containerView.isHidden = false
        
        let animationKeys = tipLabel.layer.animationKeys()
        if animationKeys != nil {
            print("有动画在运行,移除: \(animationKeys)")
            // 让上次的动画走完
            return
        }
        
        tipLabel.text = count == 0 ? "没有微博数据" : "加载了 \(count) 条微博"
        // 动画
        UIView.animate(withDuration: 1, animations: { 
            self.tipLabel.frame.origin.y = 0
            }) { (_) in
                UIView.animate(withDuration: 1, delay: 0.5, options: [], animations: { 
                    self.tipLabel.frame.origin.y = -44
                    
                    }, completion: { (_) in
                        self.containerView.isHidden = true
                })
        }
    }
    
    /// 加载更多数据
    private func loadMoreStatus() -> Void {
        // 获取微博最小的id
        let max_id = statusVMs?.last?.status.id ?? 0
        
        // 没有数据
        if max_id == 0 {
            print("id为0不能上拉加载更多数据")
            return
        }
        
        // 加载更多微博数据
        HMStatusListViewModel.shared.loadStatus(since_id: 0, max_id: max_id) { (statusVMs: [HMStatusViewModel]?, error: Error?) in
            
            // 停止上拉加载数据动画
            self.tableView.infiniteScrollingView.stopAnimating()
            
            if error != nil {
                print("上拉刷新数据失败: \(max_id)")
                SVProgressHUD.showError(withStatus: "上拉刷新数据失败")
                return
            }
            
            // 上拉加载数据成功
            print("上拉加载数据成功 = \(statusVMs?.count)")
            self.statusVMs = self.statusVMs! + statusVMs!
        }
    }
    
    private func setupTabelView() -> Void {
        tableView.delegate = self
        // 注册可重用 cell
        tableView.register(UINib(nibName: "HMStatusOriginalCell", bundle: nil), forCellReuseIdentifier: OriginalCellIdentifier)
        tableView.register(UINib(nibName: "HMStatusRetweetCell", bundle: nil), forCellReuseIdentifier: RetweetCellIdentifier)
        
//        tableView.rowHeight = UITableViewAutomaticDimension
//        tableView.estimatedRowHeight = 200
        tableView.separatorStyle = UITableViewCellSeparatorStyle.none
        
        tableView.addSubview(refreshView)
        
        refreshView.pullToRefreshHandler = {
            self.loadNewData()
        }
        
        refreshView.beginRefreshing()
    }

    private func setupNavigation() -> Void {
        // 设置导航栏左右按钮
        navigationItem.leftBarButtonItem = UIBarButtonItem(imageName: "navigationbar_friendsearch", highlightedImageName: "navigationbar_friendsearch_highlighted")
        
        // 设置导航栏右按钮
        navigationItem.rightBarButtonItem = UIBarButtonItem(imageName: "navigationbar_pop", highlightedImageName: "navigationbar_pop_highlighted")
        
        // 设置导航栏标题
        let button = HMHomeTitleView(title: "iOS")
        button.addTarget(self, action: #selector(homeTitleButtonClick(button:)), for: UIControlEvents.touchUpInside)
        navigationItem.titleView = button
    }
    
    // MARK: - 按钮点击事件
    @objc private func homeTitleButtonClick(button: UIButton) -> Void {
        // 改变按钮的状态
//        if button.isSelected {
//            button.isSelected = false
//        } else {
//            button.isSelected = true
//        }
        
        button.isSelected = !button.isSelected

        // 根据不同状态设置箭头旋转角度
        var transform: CGAffineTransform
        if button.isSelected {
            /*
             UIView旋转动画的特点:
             1.就近原则,如果需要旋转 270°, 360 - 270 = 90, 它会就近旋转90
             2.两边一样远,就顺时针
             */
            transform = CGAffineTransform(rotationAngle: CGFloat(M_PI - 0.001))
        } else {
            transform = CGAffineTransform.identity
        }
        
        UIView.animate(withDuration: 0.25) { 
            button.imageView?.transform = transform
        }
    }
    
    /// 下拉刷新控件
    private lazy var refreshView: HMPullDownRefreshView = HMPullDownRefreshView()
    
    /// 下拉刷新提示view
    private lazy var tipLabel: UILabel = {
        let tipLabelHeight: CGFloat = 44
        
        let tipLabel = UILabel(frame: CGRect(x: 0, y: -tipLabelHeight, width: UIScreen.width, height: tipLabelHeight))

        tipLabel.backgroundColor = UIColor.orange
        tipLabel.textColor = UIColor.white
        tipLabel.font = UIFont.systemFont(ofSize: 16)
        tipLabel.textAlignment = NSTextAlignment.center
        
        // 导航栏的frame = (0 20; 375 44)
        self.containerView.addSubview(tipLabel)
        
        return tipLabel
    }()
    
    private lazy var containerView: UIView = {
        let view = UIView()
        
        // 导航栏的frame = (0 20; 375 44)
        view.frame = CGRect(x: 0, y: 44, width: UIScreen.width, height: 44)
//        view.backgroundColor = UIColor.brown
        view.clipsToBounds = true
        self.navigationController?.navigationBar.addSubview(view)
        
        return view
    }()
}


extension HMHomeViewController {
    
    override func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        let statusVM = self.statusVMs![indexPath.row]
        
//        print("statusVM.rowHeight = \(statusVM.rowHeight)")
        return statusVM.rowHeight
    }
}

extension HMHomeViewController {
    
    override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        // ? 表示如果statusVMs有值才执行statusVMs.count
        // ?? statusVMs = nil 时返回 0
        return self.statusVMs?.count ?? 0
    }
    
    override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        // 获取对应的单个微博VM
        let statusVM = self.statusVMs![indexPath.row]
        
        let cellID = statusVM.isRetweetStatus ? RetweetCellIdentifier : OriginalCellIdentifier
        let cell = tableView.dequeueReusableCell(withIdentifier: cellID, for: indexPath) as! HMStatusCell
        
        // 设置对应 Cell 的 HMStatusViewModel
        cell.statusVM = statusVM
        
        return cell
    }
}
